import os

from fastapi import APIRouter, UploadFile, File
from starlette.responses import JSONResponse

from db.mysql_db import SessionDep
from models.image import Image
from schemas.image import ImageResponse

upload = APIRouter(prefix="/upload", tags=["upload"],)

UPLOAD_URL = "./static/images"
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS


@upload.post("/", response_model=list[ImageResponse])
async def upload_image(session: SessionDep, files: list[UploadFile] = File(...), ):
    upload_images = []
    for file in files:
        if not allowed_file(file.filename):
            return {"error": "图片格式不符合要求"}, 400

        file_path = os.path.join(UPLOAD_URL, file.filename)
        with open(file_path, "wb") as f:
            f.write(file.file.read())
        image = Image(image_url=file_path)
        session.add(image)
        session.commit()
        session.refresh(image)
        upload_images.append(image)

    return upload_images


@upload.delete("/")
def delete_image(image_id: int, session: SessionDep):
    image = session.query(Image).filter(Image.id == image_id).first()
    if not image:
        return {"error": "图片不存在"}, 404
    os.remove(image.image_url)
    session.delete(image)
    session.commit()
    return JSONResponse(content={"message": "图片删除成功"}, status_code=200)
